<template>
  <div class="container">
    <el-row>
      <el-col :span="24" class="top-search">
        <el-input
          v-model="listQuery.nickName"
          :placeholder="$t('username')"
          clearable
          class="w-180"
        />
        <el-input
          :value="listQuery.memberId"
          :placeholder="$t('user_id')"
          clearable
          maxlength="18"
          class="w-180"
          @input="value => (listQuery.memberId = value.replace(/[^\d]/g, ''))"
        />

        <el-select
          v-model="listQuery.subsidyType"
          :placeholder="$t('please_select')"
          class="w-180"
        >
          <el-option :value="null" :label="$t('income_plan')" />
          <el-option
            v-for="(label, value) in SUBSIDY_TYPE_MAP"
            :value="value"
            :label="$t(label)"
            :key="value"
          />
        </el-select>

        <el-select v-model="listQuery.dt" class="w-240">
          <el-option
            v-for="(item, index) in timeOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="search()">{{
          $t('search')
        }}</el-button>
      </el-col>

      <el-col :span="24" v-show="listQuery.dt" class="top-search flex">
        <div class="m-r-20 total">
          <p>
            {{ $t('wemedia_monthly_total_gold_coins') }}:
            {{ totalObj.totalCoinSum }}
          </p>
          <p>
            {{ $t('the_total_amount_of_gold_coins_issued_per_month') }}：
          {{ totalObj.totalCoinGrantSum }}
          </p>
        </div>
        <el-button
          class="m-l-20 m-r-20"
          :class="{ 'sort-color': listQuery.orderField == 2 }"
          @click="sort(2)"
          >{{ $t('monthly_gold_coin_income') }}
          <span class="sort-arrow">
            <i
              :class="{
                'defalut-color':
                  listQuery.orderField == 2 && listQuery.sort == 1
              }"
              class="el-icon-caret-top sort-arrow__top"
            />
            <i
              :class="{
                'defalut-color':
                  listQuery.orderField == 2 && listQuery.sort != 1
              }"
              class="el-icon-caret-bottom sort-arrow__bottom"
            />
          </span>
        </el-button>
        <div class="m-r-20 total">
          <p>
            {{ $t('total_monthly_wemedia_pocket_money_earnings') }}: ${{
              totalObj.totalMoneySum
            }}
          </p>
          <p>
            {{ $t('total_monthly_pocket_money_disbursed') }}： ${{
              totalObj.totalMoneyGrantSum
            }}
          </p>
        </div>
        <el-button
          class="m-l-20 m-r-20"
          :class="{ 'sort-color': listQuery.orderField == 1 }"
          @click="sort(1)"
          >{{ $t('monthly_money_income') }}
          <span class="sort-arrow">
            <i
              :class="{
                'defalut-color':
                  listQuery.orderField == 1 && listQuery.sort == 1
              }"
              class="el-icon-caret-top sort-arrow__top"
            />
            <i
              :class="{
                'defalut-color':
                  listQuery.orderField == 1 && listQuery.sort != 1
              }"
              class="el-icon-caret-bottom sort-arrow__bottom"
            />
          </span>
        </el-button>
        <el-dropdown
          class="m-l-20"
          v-show="listQuery.dt"
          split-button
          type="primary"
          @command="toExport"
        >
          {{ $t('data_export') }}
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="0">{{
              $t('monthly_income_and_details')
            }}</el-dropdown-item>
            <el-dropdown-item :command="1">{{
              $t('monthly_increment_not_integrated')
            }}</el-dropdown-item>
            <el-dropdown-item :command="2">{{
              $t('monthly_increment_after_integration')
            }}</el-dropdown-item>
            <el-dropdown-item :command="3">
              {{ $t('big_v_invite_friends_data') }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>

    <el-row class="p-t-20 t-l-r">
      <el-col :span="20">
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          @select="switchTab"
        >
          <el-menu-item index="0">{{ $t('audit_pending') }}</el-menu-item>
          <el-menu-item index="1">{{ $t('audit_accept') }}</el-menu-item>
          <el-menu-item index="2">{{ $t('has_been_issued') }}</el-menu-item>
          <el-menu-item index="3">{{ $t('has_been_rejected') }}</el-menu-item>
          <el-menu-item index="4">{{ $t('audit_reject') }}</el-menu-item>
        </el-menu>
      </el-col>
      <el-col :span="2">
        <l-button
          v-if="activeIndex == '0'"
          type="primary"
          :disabled="!selectedRows.length"
          @click.stop="batchApprove"
        >
          {{ $t('batch_approval') }}
        </l-button>
        <l-button
          v-else-if="activeIndex == '1'"
          type="primary"
          :disabled="!selectedRows.length"
          @click.stop="batchSubsidy"
        >
          {{ $t('batch_grant_subsidy') }}
        </l-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col class="p-t-20">
        <el-table
          v-loading="listLoading"
          :data="listData"
          border
          fit
          highlight-current-row
          @selection-change="v => (selectedRows = v)"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column
            :label="$t('serial_number')"
            width="80"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{
                (listQuery.page - 1) * listQuery.size + scope.$index + 1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('billing_month')"
            prop="dt"
            align="center"
          />
          <el-table-column
            :label="$t('username')"
            prop="nickName"
            align="center"
          />
          <el-table-column
            :label="$t('user_id')"
            prop="memberId"
            align="center"
          />
          <el-table-column :label="$t('income_plan')" align="center">
            <template slot-scope="scope">
              <span>{{ $t(SUBSIDY_TYPE_MAP[scope.row.subsidyType]) }}</span>
            </template>
          </el-table-column>

          <el-table-column
            :label="$t('number_of_new_articles')"
            prop="graphicAmount"
            align="center"
          />
          <el-table-column
            :label="$t('number_of_new_videos')"
            prop="videoAmount"
            align="center"
          />
          <el-table-column
            :label="$t('add_vlog')"
            prop="smallvideoAmount"
            align="center"
          />

          <el-table-column
            :label="$t('monthly_gold_coin_income')"
            align="center"
          >
            <template slot-scope="{ row }">
              <span> {{ row.coinAmount }} </span> <br />
              <el-button
                v-if="row.coinAmount"
                size="mini"
                type="primary"
                @click="checkDetail(row)"
                >{{ $t('detail') }}</el-button
              >
            </template>
          </el-table-column>

          <el-table-column
            :label="$t('monthly_money_income') + '($)'"
            align="center"
          >
            <template slot-scope="{ row }">
              <span> {{ row.amount }} </span> <br />
              <el-button
                v-if="row.amount"
                size="mini"
                type="primary"
                @click="checkDetail(row)"
                >{{ $t('detail') }}</el-button
              >
            </template>
          </el-table-column>

          <el-table-column
            :label="$t('audit_status')"
            align="center"
            width="120"
          >
            <template slot-scope="{ row }">
              <span> {{ statusMap[row.status] }} </span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="listQuery.status != 2"
            :label="$t('operation')"
            align="center"
            width="380"
          >
            <template slot-scope="{ row }">
              <el-button
                v-if="row.status == 0 || row.status == 3 || row.status == 4"
                size="mini"
                type="primary"
                @click="passOrSubsidy(row.id, 1, row.dt)"
              >
                {{ $t('passed_audit') }}
              </el-button>

              <el-button
                v-if="row.status == 0"
                size="mini"
                type="danger"
                @click="noPass(row, false)"
              >
                {{ $t('audit_reject') }}
              </el-button>

              <el-button
                v-if="row.status == 1"
                size="mini"
                type="primary"
                @click="passOrSubsidy(row.id, 2, row.dt)"
              >
                {{ $t('grant_income') }}
              </el-button>

              <el-button
                v-if="row.status == 1"
                size="mini"
                type="danger"
                @click="toReject(row.id, false)"
              >
                {{ $t('reject_accepted_audit') }}
              </el-button>

              <el-button
                v-if="row.status == 3"
                size="mini"
                type="info"
                @click="toReject(row.id, true)"
              >
                {{ $t('reason_for_rejection') }}
              </el-button>

              <el-button
                v-if="row.status == 4"
                size="mini"
                type="info"
                @click="noPass(row, true)"
              >
                {{ $t('reason_for_not_passing') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="total > 0" class="p-t-15 block fr">
          <el-pagination
            :current-page="listQuery.page"
            :page-sizes="[20, 50, 100]"
            :page-size="listQuery.size"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="val => handlePageChange(val, 'size')"
            @current-change="val => handlePageChange(val, 'page')"
          />
        </div>
      </el-col>
    </el-row>

    <!-- 单月收益明细 -->
    <el-dialog
      :visible.sync="dialogVisible.list"
      :title="detailTitle"
      width="70%"
    >
      <h2>{{ $t('gold_coin_income') }}</h2>
      <el-table
        v-loading="detailListLoading"
        :data="coinDetailsList"
        border
        fit
        highlight-current-row
      >
        <el-table-column :label="$t('income_type')" align="center">
          <template slot-scope="{ row }">
            <span>{{ $t(INCOME_TYPE_MAP[row.incomeType]) }}</span>
          </template>
        </el-table-column>

        <el-table-column :label="$t('information_type')" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.newsType | newsTypeFilter(THAT) }}</span>
          </template>
        </el-table-column>

        <el-table-column :label="$t('income_amount')" align="center">
          <template slot-scope="{ row }">
            <span>
              {{ $t('x_coin_per_n_traffic').replace('X', row.income) }}</span
            >
          </template>
        </el-table-column>

        <el-table-column :label="$t('traffic_type')" align="center">
          <template slot-scope="{ row }">
            <span>{{ $t(FLOW_TYPE_MAP[row.flowType]) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('upper_limit')"
          prop="upLimit"
          align="center"
        />

        <el-table-column
          :label="$t('data')"
          prop="totalQuantity"
          align="center"
        />

        <el-table-column :label="$t('income')" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.amount }} {{ $t('coins') }} </span>
          </template>
        </el-table-column>
      </el-table>

      <h2 class="p-t-15">{{ $t('money_income') }}</h2>
      <el-table
        v-loading="detailListLoading"
        :data="moneyDetailsList"
        border
        fit
        highlight-current-row
      >
        <el-table-column :label="$t('income_type')" align="center">
          <template slot-scope="{ row }">
            <span>{{ $t(INCOME_TYPE_MAP[row.incomeType]) }}</span>
          </template>
        </el-table-column>

        <el-table-column :label="$t('information_type')" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.newsType | newsTypeFilter(THAT) }}</span>
          </template>
        </el-table-column>

        <el-table-column :label="$t('income_amount')" align="center">
          <template slot-scope="{ row }">
            <span>
              {{ $t('x_dollars_per_n_traffic').replace('X', row.income) }}</span
            >
          </template>
        </el-table-column>

        <el-table-column :label="$t('traffic_type')" align="center">
          <template slot-scope="{ row }">
            <span>{{ $t(FLOW_TYPE_MAP[row.flowType]) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('upper_limit')"
          prop="upLimit"
          align="center"
        />

        <el-table-column
          :label="$t('data')"
          prop="totalQuantity"
          align="center"
        />

        <el-table-column :label="$t('income')" align="center">
          <template slot-scope="{ row }">
            <span>${{ row.amount }} </span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 驳回 -->
    <el-dialog
      :title="$t('reason_for_rejection')"
      :visible.sync="dialogVisible.reject"
      width="1000px"
    >
      <el-input
        v-model="form.rejectReason"
        :disabled="disabled.reject"
        :placeholder="
          $t('please_fill_in_the_reason_for_rejection_only_for_backend_record')
        "
        :autosize="{ minRows: 6, maxRows: 10 }"
        :maxlength="MAX_LENGTH"
        type="textarea"
        class="w-800"
      />
      <div slot="footer" class="dialog-footer">
        <el-button
          v-show="!disabled.reject"
          :disabled="btnLoading.reject"
          :loading="btnLoading.reject"
          @click="dialogVisible.reject = false"
          >{{ $t('cancel') }}</el-button
        >
        <el-button
          v-show="!disabled.reject"
          :disabled="btnLoading.reject"
          :loading="btnLoading.reject"
          type="primary"
          @click="confirmAudit('reject')"
          >{{ $t('confirm') }}</el-button
        >
        <el-button
          v-show="disabled.reject"
          type="primary"
          @click="dialogVisible.reject = false"
          >{{ $t('close') }}</el-button
        >
      </div>
    </el-dialog>

    <!-- 不通过 -->
    <el-dialog
      :title="$t('reason_for_not_passing')"
      :visible.sync="dialogVisible.noPass"
      width="1000px"
    >
      <p v-show="disabled.noPass">{{ form.notApproveReason }}</p>
      <div v-show="!disabled.noPass">
        <el-radio-group
          v-model="radioValue"
          :disabled="disabled.noPass"
          class="radio_choose"
        >
          <el-radio
            v-for="item in reasonList"
            :label="item.value"
            :key="item.value"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
        <el-input
          v-model="form.notApproveReason"
          :disabled="disabled.noPass || radioValue != OTHER_LABEL_VALUE"
          :placeholder="$t('please_fill_in_the_reason_for_not_passing')"
          :autosize="{ minRows: 6, maxRows: 10 }"
          :maxlength="MAX_LENGTH"
          type="textarea"
          class="w-800"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-show="!disabled.noPass"
          :disabled="btnLoading.noPass"
          :loading="btnLoading.noPass"
          @click="dialogVisible.noPass = false"
          >{{ $t('cancel') }}</el-button
        >
        <el-button
          v-show="!disabled.noPass"
          :disabled="btnLoading.noPass"
          :loading="btnLoading.noPass"
          type="primary"
          @click="confirmAudit('noPass')"
          >{{ $t('confirm') }}</el-button
        >
        <el-button
          v-show="disabled.noPass"
          type="primary"
          @click="dialogVisible.noPass = false"
          >{{ $t('close') }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMediasubsidyListApi,
  getDateListApi,
  getDetailListApi,
  mediaAuditApi,
  getAuditReasonApi
} from '@/api/wemediaRevenueAnalysis.js';
import { getLanguage } from '@/lang/index';
import {
  FLOW_TYPE_MAP,
  INCOME_TYPE_MAP,
  NEWS_TYPES_MAP,
  SUBSIDY_TYPE_MAP
} from '@/constants/index.js';
import { getToken } from '@/utils/auth';

const MAX_LENGTH = 1000;
const OTHER_LABEL_VALUE = 'OTHERS';
const LanMap = {
  zh: 'zh-Hans',
  en: 'en-US',
  km: 'km-KH'
};

export default {
  filters: {
    newsTypeFilter(val, that) {
      if (!val || val == null) return val;
      let res = '';
      const arr = val.split(',');
      arr.forEach(item => {
        res += `${that.$t(NEWS_TYPES_MAP[item])} `;
      });

      return res;
    }
  },

  data() {
    return {
      SUBSIDY_TYPE_MAP,
      MAX_LENGTH,
      THAT: this,
      NEWS_TYPES_MAP,
      LanMap,
      OTHER_LABEL_VALUE,
      FLOW_TYPE_MAP,
      INCOME_TYPE_MAP,
      reasonList: [
        {
          label: this.$t('sorry_there_is_an_abnormality_in_your_wemedia'),
          value: this.$t('sorry_there_is_an_abnormality_in_your_wemedia')
        },
        {
          label: this.$t('custom'),
          value: OTHER_LABEL_VALUE
        }
      ],
      dialogVisible: {
        list: false,
        noPass: false,
        reject: false
      },
      timeOptions: [],
      listQuery: {
        memberId: null,
        nickName: null,
        isFlag: null, //  0非自媒体,1普通自媒体，2大V
        subsidyType: null,
        orderField: '', // 1零钱 2 金币
        dt: null,
        sort: 1, //  1-根据amount降序，0-根据amount升序
        lan: null, // 中文-zh-Hans 英文-en-US 柬文-km-KH
        status: 0, // 0：未审核，1：通过审核，2：已发钱，3：驳回审核；4：不通过
        page: 1,
        size: 20
      },
      activeIndex: '0',
      listLoading: false,
      listData: [],
      total: 1,
      btnLoading: {
        reject: false,
        noPass: false
      },
      moneyDetailsList: [],
      coinDetailsList: [],
      detailListLoading: false,
      disabled: {
        reject: true,
        noPass: true
      },
      form: {
        id: null,
        status: null,
        rejectReason: null, // 驳回理由
        notApproveReason: null // 不通过理由
      },
      radioValue: OTHER_LABEL_VALUE,
      userLevelMap: {
        1: this.$t('general_self_media_users'),
        2: this.$t('big_v_self_media_users')
      },
      statusMap: {
        0: this.$t('audit_pending'),
        1: this.$t('audit_accept'),
        2: this.$t('has_been_issued'),
        3: this.$t('has_been_rejected'),
        4: this.$t('audit_reject')
      },
      detailTitle: null,
      selectedDate: null, // 搜索的日期
      currentMonth: null, // 当前月份
      totalObj: {
        totalMoneyGrantSum: null, // 月发放零钱总额
        totalCoinGrantSum: null, // 月发放金币总额
        totalCoinSum: null, // 月自媒体金币收益总额
        totalMoneySum: null // 月自媒体零钱收益总额
      },
      selectedRows: []
    };
  },

  created() {
    const lan = getLanguage();
    this.listQuery.lan = this.LanMap[lan];
    this.getDateList();
  },

  methods: {
    async getDateList() {
      try {
        const timeOptions = [
          {
            value: null,
            label: this.$t('all_date')
          }
        ];
        const { code, data } = await getDateListApi();
        if (code == 200) {
          const arr = data || [];
          arr.forEach((item, index) => {
            const obj = {
              value: item,
              label: item
            };
            timeOptions.push(obj);
            if (index == 0) {
              this.listQuery.dt = item;
              this.getList();
            }
          });
          this.timeOptions = timeOptions;
        } else {
          this.$message.warning(this.$t('there_was_an_error_in_the_request'));
        }
        // eslint-disable-next-line no-empty
      } catch (e) {}
    },

    async getList() {
      this.listLoading = true;
      try {
        const { code, data } = await getMediasubsidyListApi(this.listQuery);
        this.listLoading = false;
        this.selectedDate = this.listQuery.dt;
        if (code == 200) {
          this.listData = data.result || [];
          this.total = Number(data.count) || 0;
          this.totalObj = {
            totalMoneyGrantSum: Number(data.totalMoneyGrantSum) || 0,
            totalCoinGrantSum: Number(data.totalCoinGrantSum) || 0,
            totalCoinSum: Number(data.totalCoinSum) || 0,
            totalMoneySum: Number(data.totalMoneySum) || 0
          };
        }
      } catch (e) {
        this.listLoading = false;
      }
    },

    search() {
      this.listQuery.page = 1;
      this.getList();
    },

    async checkDetail(row) {
      this.dialogVisible.list = true;
      const { lan } = this.listQuery;
      const { nickName, memberId, dt } = row;
      const query = {
        dt,
        lan,
        memberId
      };

      this.detailTitle = '';
      this.detailListLoading = true;
      try {
        const { code, data } = await getDetailListApi(query);
        this.detailListLoading = false;
        if (code == 200) {
          this.coinDetailsList = data.coinDetails || [];
          this.moneyDetailsList = data.moneyDetails || [];
          const { coinTotalAmount = 0, moneyTotalAmount = 0 } = data;
          this.detailTitle = this.$t('total_revenue_details_of_aaa_in_bbb_c')
            .replace('X', nickName)
            .replace('Y', dt)
            .replace('Z', moneyTotalAmount)
            .replace('CCC', coinTotalAmount);
        }
      } catch (e) {
        this.detailListLoading = false;
      }
    },

    sort(key) {
      if (this.listLoading) return;
      const { sort, orderField } = this.listQuery;
      if (key === orderField) {
        this.listQuery.sort = sort == 1 ? 0 : 1;
      } else {
        this.listQuery.orderField = key;
        this.listQuery.sort = 1;
      }

      this.getList();
    },

    toExport(exportType) {
      const xhh = new XMLHttpRequest();
      xhh.open(
        'post',
        `${process.env.BASE_API}/v1/analysis/mediasubsidy/export`
      );
      xhh.setRequestHeader('X-Token', getToken());
      xhh.setRequestHeader('content-type', 'application/json;charset=UTF-8');
      xhh.responseType = 'blob';
      xhh.onreadystatechange = function () {
        if (xhh.readyState === 4 && xhh.status === 200) {
          const blob = new Blob([xhh.response]);
          const csvUrl = URL.createObjectURL(blob);
          const link = document.createElement('a');
          let fileName = xhh
            .getResponseHeader('Content-Disposition')
            .split(';')[1]
            .split('filename=')[1];
          const fileNameUnicode = xhh
            .getResponseHeader('Content-Disposition')
            .split('filename*=')[1];
          if (fileNameUnicode) {
            fileName = decodeURIComponent(fileNameUnicode.split("''")[1]);
          }

          document.body.appendChild(link);
          link.href = csvUrl;
          link.target = '_blank';
          link.id = 'linkId';
          link.className = 'linkId';
          link.download = decodeURI(fileName);
          document.getElementById('linkId').click();
          link.remove();
        }
      };
      const query = { ...this.listQuery, page: 1, size: 100000, exportType };
      xhh.send(JSON.stringify(query));
    },

    switchTab(val) {
      this.activeIndex = val;
      this.listQuery.status = val;
      this.listQuery.page = 1;
      this.getList();
    },

    handlePageChange(val, key) {
      this.listQuery[key] = val;
      this.getList();
    },

    getBatchOptions() {
      const getMonth = dt => {
        const { 1: month } = dt.split('-');
        return month;
      };
      return this.selectedRows.map(t => ({ id: t.id, month: getMonth(t.dt) }));
    },

    async batchApprove() {
      await this.$confirm(
        this.$t('are_you_sure_you_want_to_batch_pass_the_audit'),
        this.$t('tips'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning',
          center: true
        }
      );
      const rows = this.getBatchOptions().map(t => ({ ...t, status: 1 }));
      await this.batchAudit(rows);
    },

    async batchSubsidy() {
      await this.$confirm(
        this.$t('are_you_sure_to_batch_pay_the_subsidy_to_the_user_wallet'),
        this.$t('tips'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning',
          center: true
        }
      );
      const rows = this.getBatchOptions().map(t => ({ ...t, status: 2 }));
      await this.batchAudit(rows);
    },

    async batchAudit(rows) {
      const audit = async options => {
        try {
          const res = await mediaAuditApi(options);
          if (res.state !== 1) {
            throw new Error(res.error_msg);
          }
        } catch (e) {
          this.$message.error(e.$message);
        }
      };

      await Promise.all(rows.map(audit));
      this.$message.success(this.$t('operation_successful'));
      await this.getList();
    },

    // status: 1 通过审核 2发放补贴
    async passOrSubsidy(id, status, dt) {
      const title =
        status == 1
          ? this.$t('are_you_sure_you_want_to_pass_the_audit')
          : this.$t('are_you_sure_to_pay_the_subsidy_to_the_user_wallet');
      const month = dt.split('-')[1];
      try {
        const action = await this.$confirm(title, this.$t('tips'), {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning',
          center: true
        });

        if (action === 'confirm') {
          const query = {
            id,
            status,
            month,
            rejectReason: null,
            notApproveReason: null,
            notApproveReasonType: null
          };
          this.audit(query);
        }
        // eslint-disable-next-line no-empty
      } catch (e) {}
    },

    noPass(row, disabled) {
      const { id, dt } = row;
      const title = this.$t(
        'sorry_there_is_an_abnormality_in_your_wemedia'
      ).replace('N', dt);
      // eslint-disable-next-line prefer-destructuring
      this.currentMonth = dt.split('-')[1];
      this.reasonList[0] = {
        label: title,
        value: title
      };

      this.disabled.noPass = disabled;
      this.form = {
        id,
        status: 4,
        notApproveReason: null,
        rejectReason: null
      };
      if (!disabled) {
        this.radioValue = title;
        this.dialogVisible.noPass = true;
      } else {
        this.getReason(id, 'noPass');
      }
    },

    toReject(id, disabled) {
      this.disabled.reject = disabled;
      this.form = {
        id,
        status: 3,
        notApproveReason: null,
        rejectReason: null
      };

      if (!disabled) {
        this.dialogVisible.reject = true;
      } else {
        this.getReason(id, 'reject');
      }
    },

    async getReason(id, name) {
      try {
        const { state, result, error_msg } = await getAuditReasonApi({ id });
        if (state == 1) {
          const { rejectReason, notApproveReason } = result || {};
          this.form.rejectReason = rejectReason;
          this.form.notApproveReason = notApproveReason;
          this.dialogVisible[name] = true;
        } else {
          this.$message.warning(error_msg);
        }
        // eslint-disable-next-line no-empty
      } catch (e) {}
    },

    //  "status": 0：未审核，1：通过审核，2：发钱，3：驳回审核，4：不通过
    async audit(query, name) {
      if (this.btnLoading[name]) return;
      this.btnLoading[name] = true;
      try {
        const { state, error_msg } = await mediaAuditApi(query);
        this.btnLoading[name] = false;
        if (state == 1) {
          this.$message.success(this.$t('operation_successful'));
          this.getList();
        } else {
          this.$message.warning(error_msg);
        }
      } catch (e) {
        this.btnLoading[name] = false;
      }
    },

    async confirmAudit(name) {
      const { radioValue, OTHER_LABEL_VALUE } = this;
      const { notApproveReason, rejectReason } = this.form;

      if (
        name == 'noPass' &&
        radioValue == OTHER_LABEL_VALUE &&
        (!notApproveReason || notApproveReason == null)
      ) {
        this.$message.warning(
          this.$t('the_reason_for_not_passing_cannot_be_empty')
        );
        return;
      }

      if (name == 'reject' && (!rejectReason || rejectReason == null)) {
        this.$message.warning(this.$t('rejection_reason_cannot_be_empty'));
        return;
      }

      if (this.btnLoading[name]) return;
      this.btnLoading[name] = true;
      const month = name == 'reject' ? null : this.currentMonth;
      const notApproveReasonType =
        name == 'reject' ? null : radioValue == OTHER_LABEL_VALUE ? 1 : 0;
      const reason =
        radioValue == OTHER_LABEL_VALUE ? notApproveReason : radioValue;
      const query = {
        ...this.form,
        notApproveReason: reason,
        month,
        notApproveReasonType
      };

      try {
        const { state, error_msg } = await mediaAuditApi(query);
        this.btnLoading[name] = false;
        if (state == 1) {
          this.$message.success(this.$t('operation_successful'));
          this.dialogVisible[name] = false;
          this.getList();
        } else {
          this.$message.warning(error_msg);
        }
      } catch (e) {
        this.btnLoading[name] = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 15px;

  .top-search {
    margin: 10px 0;

    label {
      font-size: 12px;
      font-weight: 400;
      margin-right: 5px;
    }
  }
  .t-l-r {
    text-align: right;
  }

  .w-180 {
    width: 180px;
  }

  .w-400 {
    width: 400px;
  }

  h2 {
    font-size: 24px;
    line-height: 2;
  }

  .flex {
    display: flex;

    .total {
      text-align: left;
    }
  }

  .m-r-20 {
    margin-right: 20px;
  }

  .sort-arrow {
    padding-right: 10px;

    &__top {
      position: absolute;
      top: 78px;
    }

    &__bottom {
      position: absolute;
      top: 86px;
    }
  }

  .defalut-color {
    color: #606266;
  }

  .sort-color {
    color: #409eff !important;
  }

  .radio_choose {
    margin: 0 0 10px 0;

    .el-radio {
      display: block;
      padding: 5px 0;
      white-space: normal;
    }
  }
}
</style>
